package cn.tedu.sp06.filter;


import cn.tedu.web.util.JsonResult;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;


@Component
public class AccessFilter extends ZuulFilter {
    //设置过滤器的类型  post get。。
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    //设置过滤器的顺序号
    @Override
    public int filterOrder() {
        return 6;
    }

    @Override
    public boolean shouldFilter() {
        /**
         * 请求商品，需要判断权限
         * 请求其他模块，跳过权限判断直接访问
         */
        //获取请求的上下文对象
        RequestContext ctx = RequestContext.getCurrentContext();
        //从上下文对象获取正在进行的服务   ServiceId
        Object serviceId = ctx.get(FilterConstants.SERVICE_ID_KEY);

        //如果ServiceId是ItemService 返回true
        return false;
    }

    @Override
    public Object run() throws ZuulException {
        /**
         * 获得请求上下文对象
         */
        RequestContext ctx = RequestContext.getCurrentContext();
        //获取参数
        HttpServletRequest request = ctx.getRequest();
        String token = request.getParameter("token");
        //判断token 是否是空或者null或者空格
        if(StringUtils.isBlank(token)){
            ctx.setSendZuulResponse(false);//阻止继续调用
            ctx.addZuulResponseHeader("Context-Type", "application/json;charset=utf-8");
            String json = JsonResult.build().code(400).msg("未登录").toString();
            ctx.setResponseBody(json);
        }
        //登录成功返回空
        return null;
    }
}
